using System.Threading.Tasks;
using DailyPoetryX.Services;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;

namespace DailyPoetryX.ViewModels {
    /// <summary>
    /// 主页ViewModel。
    /// </summary>
    public class MainPageViewModel : ViewModelBase {
        /******** 构造函数 ********/

        /// <summary>
        /// 诗词存储。
        /// </summary>
        private IPoetryStorage poetryStorage;

        /// <summary>
        /// 偏好存储。
        /// </summary>
        private IFavoriteStorage favoriteStorage;

        /// <summary>
        /// 根导航服务。
        /// </summary>
        private IRootNavigationService rootNavigationService;

        /// <summary>
        /// 主页ViewModel。
        /// </summary>
        /// <param name="poetryStorage">诗词存储。</param>
        /// <param name="favoriteStorage">偏好存储。</param>
        /// <param name="rootNavigationService">根导航服务。</param>
        public MainPageViewModel(IPoetryStorage poetryStorage,
            IFavoriteStorage favoriteStorage,
            IRootNavigationService rootNavigationService) {
            this.poetryStorage = poetryStorage;
            this.favoriteStorage = favoriteStorage;
            this.rootNavigationService = rootNavigationService;
        }

        /******** 绑定属性 ********/

        /******** 绑定命令 ********/

        /// <summary>
        /// 页面显示命令。
        /// </summary>
        public RelayCommand PageAppearingCommand =>
            _pageAppearingCommand ?? (_pageAppearingCommand = new RelayCommand(
                async () => await PageAppearingCommandFunction()));

        /// <summary>
        /// 页面显示命令。
        /// </summary>
        private RelayCommand _pageAppearingCommand;

        internal async Task PageAppearingCommandFunction() {
            var run = false;

            if (!pageLoaded) {
                lock (pageLoadedLock) {
                    if (!pageLoaded) {
                        pageLoaded = true;
                        run = true;
                    }
                }
            }

            if (!run) return;

            if (!poetryStorage.Initialized() ||
                !favoriteStorage.Initialized()) {
                await rootNavigationService.NavigateToAsync(
                    RootNavigationServiceConstants.InitializationPage);
                return;
            }

            await rootNavigationService.NavigateToAsync(
                RootNavigationServiceConstants.TodayPage);
        }

        /******** 私有变量 ********/

        /// <summary>
        /// 页面已加载。
        /// </summary>
        private volatile bool pageLoaded;

        /// <summary>
        /// 页面已加载锁。
        /// </summary>
        private readonly object pageLoadedLock = new object();
    }
}